var express = require('express');
var router = express.Router();
var {UserModel,RoleModel} =require('../db/model')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 搜索所有用户列表
router.get('/userlist',async (res,req)=>{
  let data=await UserModel.aggregate([
    {
      $lookup:{
        from:"role",// 连接表
        localField: "role",// 主表关联字段
        foreignField: "_id",// 连接表关联字段
        as: "roles"// 别名，数组形式显示
      }
    }
  ])
  console.log(data);
  req.send({
    code:200,
    data:data
  })
})

// 搜索所有单个用户
router.get('/userone',async (res,req)=>{
  let id=res.query.id
  let data=await UserModel.aggregate([
    {
      $lookup:{
        from:"role",// 连接表
        localField: "role",// 主表关联字段
        foreignField: "_id",// 连接表关联字段
        as: "roles"// 别名，数组形式显示
      }
    }
  ])
  let onedata=data.filter((item)=>{
    return item._id==id
  })
  console.log(onedata);
  req.send({
    code:200,
    data:onedata
  })
})


// 修改单个用户
router.post('/upuserone',async (res,req)=>{
  let id=res.query.id
  let updata=res.body
  let data =await UserModel.updateOne({_id:id},updata)
  req.send({
    code:200,
    data:data
  })
})


// 添加用户列表
router.post('/adduser',async (res,req)=>{
  let resdata=res.body
  console.log(resdata);
  let data=await UserModel.create(resdata)
  req.send({
    code:200,
    data:data
  })
})

// 删除单个用户
router.post('/deluser',async (res,req)=>{
  let id=res.query.id
  let data=await UserModel.deleteOne({_id:id})
  req.send({
    code:200,
    data:data
  })
})



// 搜索角色列表
router.get('/rolelist',async (res,req)=>{
  let data=await RoleModel.find()
  console.log(data);
  req.send({
    code:200,
    data:data
  })
})
// 添加用户列表
router.post('/addrole',async (res,req)=>{
  let resdata=res.body
  console.log(rolename);
  let data =await RoleModel.create(resdata)
  req.send({
    code:200,
    data:data
  })
})







module.exports = router;
